package com.link.base.base.position.service;

import com.link.base.basic.dao.mybatis.mapper.BasicCommonMapper;
import com.link.base.basic.model.ListOfValue;
import com.link.base.ext.emp.model.ExtEmployee;
import com.link.base.user.model.CoreUser;
import com.link.base.base.dept.dao.mybatis.mapper.DepartmentMapper;
import com.link.base.base.dept.model.Department;
import com.link.base.base.mvg.dao.mybatis.user.mapper.UserPostnMvgMapper;
import com.link.base.base.mvg.model.Mvg;
import com.link.base.base.position.dao.mybatis.mapper.PositionMapper;
import com.link.base.base.position.model.Position;
import com.link.base.base.user.service.UserService;
import com.link.core.cllog.LCLogger;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.query.Filter;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.ServiceException;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.util.StringUtils;
import com.link.core.util.UserUtil;
import com.link.base.core.basic.util.YmlConstants;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author unknown
 * @date unknown
 * @comments 职位服务
 */
@Service
public class PositionServiceImpl extends BasicServiceImpl<Position> implements PositionService {

    @Resource
    public UserPostnMvgMapper userPostnMvgMapper;
    @Resource
    private PositionMapper positionMapper;
    @Resource
    private BasicCommonMapper basicCommonMapper;
    @Resource
    private DepartmentMapper departmentMapper;
    @Resource
    private UserService userService;

    @Override
    public BasicMapper<Position> getBasicMapper() {
        return positionMapper;
    }

    @Override
    public List<Position> queryPositionListRemoveIdAndChildrenPage(Position entity) throws Exception {
        String dataBase = "mysql";
        if (StringUtils.equals(YmlConstants.getApplicationDatabase(), dataBase)) {
            String str = positionMapper.getPostnChildStr(entity);
            entity.setAttr6(str);
        }
        return positionMapper.queryPositionListRemoveIdAndChildrenPage(entity);
    }

    @Override
    public Position queryRoot(Position entity) throws Exception {
        return positionMapper.queryRoot(entity);
    }

    @Override
    public List<Position> queryByUserPage(Position entity) throws Exception {
        return positionMapper.queryByUserPage(entity);
    }

    @Override
    public void queryTreeByRoot(Position entity) throws Exception {
        treePositionList(entity);
    }

    /**
     * 递归查询职位树结构
     *
     * @throws ServiceException
     */
    private void treePositionList(Position entity) throws Exception {
        Position t = new Position();
        CoreUser user = UserUtil.getUser();
        t.setLoginCorpId(user.getLoginCorpId());
        t.setPageFlag(false);
        List<Position> tempList = positionMapper.queryByExamplePage(t);
        /*for (Position temp : tempList) {
            treePositionList(temp);
        }*/
        printTreePositionList(tempList, entity);
    }

    private void printTreePositionList(List<Position> tempList, Position entity) throws ServiceException {
        if (entity.getId() == null) {
            throw new ServiceException("POSITION-003");
        }
        List<Position> childList = new ArrayList<>();
        for (Position temp : tempList) {
            if (entity.getId().equals(temp.getParentPositionId())) {
                childList.add(temp);
            }
        }
        entity.setChildren(childList);
        for (Position position : childList) {
            printTreePositionList(tempList, position);
        }
    }

    /**
     * 用于画结构图
     */
    @Override
    public void queryTreeByRoot1(Position entity) throws Exception {
        treePositionList1(entity);
    }

    private void treePositionList1(Position entity) throws Exception {
        ListOfValue record = new ListOfValue();
        record.setType("POSTN_TYPE");
        record.setVal(entity.getPositionType());
        record = basicCommonMapper.getLovName(record);
        entity.setPositionType(record.getName());

        QueryParams params = new QueryParams();
        params.addFilter(new Filter("parentPositionId", String.valueOf(entity.getId())));
        params.setPageFlag(false);
        Position t = (Position) BasicModel.transformClass(Position.class, params);
        List<Position> tempList = positionMapper.queryByExamplePage(t);
        for (Position temp : tempList) {
            record.setVal(temp.getPositionType());
            record = basicCommonMapper.getLovName(record);
            temp.setPositionType(record.getName());
            treePositionList1(temp);
        }
        entity.setChildren(tempList);
    }

    @Override
    public void beforUpsert(Position entity) throws Exception {
        super.beforUpsert(entity);
        if (StringUtils.isBlank(entity.getIsEffective())) {
            entity.setIsEffective("Y");
        }
    }

    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void insert(Position entity) throws ServiceException {
        try {
            QueryParams params = new QueryParams();
            Position t = (Position) BasicModel.transformClass(Position.class, params);
            t.setIntegrationId(entity.getIntegrationId());
            //如果父职位没有指定，则添加默认父职位
            if (entity.getParentPositionId() == null) {
                t.setLoginCorpId(entity.getLoginCorpId());
                //获取根职位的ID
                Position rootPosition = positionMapper.queryRoot(t);
                if (null == rootPosition) {
                    throw new ServiceException("POSITION-004",t.getLoginCorpId().toString());
                }
                Long parentPositionId = rootPosition.getId();
                entity.setParentPositionId(parentPositionId);
            }
            //如果部门没有指定，则添加默认部门
            if (entity.getDeptId() == null) {
                Department rootDepartment = departmentMapper.queryRoot(new Department());
                if (null == rootDepartment) {
                    throw new ServiceException("POSITION-005");
                }
                //获取根部门的ID
                Long parentDeptId = rootDepartment.getId();
                //添加默认部门
                entity.setDeptId(parentDeptId);
            }
            super.insert(entity);
        } catch (Exception e) {
            LCLogger.withException(e);
            throw new ServiceException("POSITION-001");
        }
    }

    @Override
    public void upsert(Position entity) throws Exception {
        super.upsert(entity);
        //同时修改用户的主要职位
        Long postnId = entity.getId();
        Long userId = entity.getUserId();
        if (userId != null) {
            QueryParams qps = new QueryParams();
            qps.setPageFlag(false);
            qps.addFilter(new Filter("id", String.valueOf(postnId)));
            Mvg mvgParam = (Mvg) BasicModel.transformClass(Mvg.class, qps);
            mvgParam.setMvgParentId(userId);
            List<HashMap<String, String>> postnMapList = userPostnMvgMapper.queryRightListPage(mvgParam);
            if (postnMapList.size() == 1) {
                userService.mainPostnUpdate(userId, postnId);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void deleteWithChildById(Position entity) throws Exception {
        beforDelete(entity);
        checkId(entity);
        QueryParams params = new QueryParams();
        params.setLoginCorpId(UserUtil.getUser().getLoginCorpId());
        params.setPageFlag(false);
        removeWithChilds(entity, params);
    }

    /**
     * 递归删除
     */
    private void removeWithChilds(Position entity, QueryParams params) throws Exception {
        deleteById(entity);
        params.addFilter(new Filter("parentPositionId", String.valueOf(entity.getId())));
        Position t = (Position) BasicModel.transformClass(Position.class, params);
        List<Position> list = positionMapper.queryByExamplePage(t);
        for (Position position : list) {
            this.removeWithChilds(position, params);
        }
    }

    @Override
    public void mainUserUpdate(Long postnId, Long userId) throws Exception {
        Position entity = new Position();
        entity.setId(postnId);
        entity.setUserId(userId);
        positionMapper.mainUserUpdate(entity);
    }

    /**
     * @通过集成ID查询职位
     * @author huanglongjian
     * @date 2017年11月30日
     */
    @Override
    public Position queryByIntegrationId(Position entity) throws Exception {
        Position postn = positionMapper.queryByIntegrationId(entity);
        return postn;
    }

    /**
     * @param postion
     * @return list
     * @throws Exception
     * @author huanglongjian
     * @ 查询客户的职位
     */
    @Override
    public List<Position> queryByAccntId(Position postion) throws Exception {
        List<Position> posList = null;
        posList = positionMapper.queryByAccntId(postion);
        return posList;
    }

    @Override
    public Position queryUniquePosition(Position position) {
        return positionMapper.queryUniquePositionByPosntCode(position);
    }

    @Override
    public Position queryUniqueShrParOrgnization(Position position) {
        return positionMapper.queryUniqueShrParPosition(position);
    }

    @Override
    public void updateForEsb(Position position) {
        positionMapper.updateForEsb(position);
    }

    @Override
    public Position queryEmpPositionByEmp(ExtEmployee employee) {
        return positionMapper.queryEmpPositionByEmp(employee);
    }

    @Override
    public Position queryPositionByPostnCode(String postnCode) {
        return positionMapper.queryPositionByPostnCode(postnCode);
    }

    @Override
    public List<Position> queryUserPostnById(Position t) {
        return positionMapper.queryUserPostnById(t);
    }

}
